﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TYStudioDemo.Interfaces;
using TYStudioDemo.Models;

namespace TYStudioDemo.Repositories
{
    public class TYRepository<T> : ITYRepository<T> where T : class
    {
        protected ObjectContext _context;

        private IObjectSet<T> _objectSet;

        public TYRepository()
        {
            //总是返回当前的datacontext，详细说明请看教程的Models篇
            _context = TYEntities.Current;
            _objectSet = _context.CreateObjectSet<T>();
        }

        public IQueryable<T> Fetch()
        {
            return _objectSet.AsQueryable<T>();
        }

        public IEnumerable<T> GetAll()
        {
            return Fetch().AsEnumerable<T>();
        }

        public IEnumerable<T> Find(Func<T, bool> predicate)
        {
            return _objectSet.Where<T>(predicate);
        }

        public T Single(Func<T, bool> predicate)
        {
            return _objectSet.Single<T>(predicate);
        }

        public T SingleOrDefault(Func<T, bool> predicate)
        {
            return _objectSet.SingleOrDefault<T>(predicate);
        }

        public T First(Func<T, bool> predicate)
        {
            return _objectSet.First<T>(predicate);
        }

        public void Delete(T entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            _objectSet.DeleteObject(entity);
        }

        public void Create(T entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }
            _objectSet.AddObject(entity);
        }

        public void Attach(T entity)
        {
            _objectSet.Attach(entity);
        }
    }
}
